<template>
  <div>
    <input
      class="input-frame"
      ref="fileInput"
      type="file"
      id="file"
      name="file"
      accept="image/png, image/jpeg, image/gif, image/jpg"
      @change="handleFileChange"
    />
  </div>
</template>

<script setup>
import { UserAxios } from "@/api/user";
//import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { ref, defineEmits } from "vue";
import { UserStore } from "@/store";
import Pubsub from "pubsub-js";
import { PubSubEnum } from "@/types";
const userStore = UserStore();
// const s3Client = new S3Client({
//   region: "ap-southeast-1",
//   credentials: {
//     accessKeyId: "AKIA47CR25P7DI5FY5HY",
//     secretAccessKey: "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",
//   },
// });

const chooseFile = () => {
  fileInput.value.click();
};

const fileInput = ref(null);
const selectedFile = ref(null);

const handleFileChange = event => {
  selectedFile.value = event.target.files[0];
  //将input读取到的File格式的图片文件 转为base64提供访问
  convertFileToUrl(event.target.files[0]);
  Pubsub.publish(PubSubEnum.SHOW_LOADING);
};
const convertFileToUrl = file => {
  const reader = new FileReader();
  reader.onload = e => {
    let imageUrl = e.target.result;
    // console.log("imageUrl", imageUrl);
    // 文件读取完成后，将结果发送给父组件
    uploadFile();
  };
  reader.readAsDataURL(file);
};

const uploadFile = async () => {
  if (!selectedFile.value) return console.log("未选择文件");
  try {
    // const bucketName = "hy-bucket11";
    // const key = `uploads/${selectedFile.value.name}`;

    // const params = {
    //   Bucket: bucketName,
    //   Key: key,
    //   Body: selectedFile.value,
    // };

    // const command = new PutObjectCommand(params);
    // await s3Client.send(command);

    // const avatar =
    //   "https://hy-bucket11.s3.ap-southeast-1.amazonaws.com/uploads/" + selectedFile.value.name;
    // UserAxios.updateUserInfo({ avatar: avatar })
    //   .then(res => {
    //     emit("file-chosen", avatar);
    //     userStore.$patch({
    //       userLoginInfo: {
    //         profile: {
    //           avatar: avatar,
    //         },
    //       },
    //       userInfoDetails: {
    //         profile: {
    //           avatar: avatar,
    //         },
    //       },
    //     });
    //     Pubsub.publish(PubSubEnum.SHOW_SUCCESS_TIP);
    //     Pubsub.publish(PubSubEnum.HIDE_LOADING);
    //   })
    //   .finally(() => {
    //     Pubsub.publish(PubSubEnum.HIDE_LOADING);
    //   });
    const fix = new Date().getTime() + "." + selectedFile.value.name.split(".")[1];
    const params = {
      dir: "uploadsGame", // 存储路径目录
      fix, // 文件后缀
    };
    // 请求后端生成预签名 URL
    const { url, fileUrl } = await UserAxios.getS3TempToken(params);
    if (url) {
      // 使用预签名 URL 上传文件
      const uploadResponse = await fetch(url, {
        method: "PUT",
        body: selectedFile.value, // 确保正确传递文件
        headers: {
          "Content-Type": selectedFile.value.type || "application/octet-stream", // 设置正确的内容类型
        },
      });
      if (uploadResponse.ok) {
        UserAxios.updateUserInfo({ avatar: fileUrl })
          .then(res => {
            emit("file-chosen", fileUrl);
            userStore.$patch({
              userLoginInfo: {
                profile: {
                  avatar: fileUrl,
                },
              },
              userInfoDetails: {
                profile: {
                  avatar: fileUrl,
                },
              },
            });
            Pubsub.publish(PubSubEnum.SHOW_SUCCESS_TIP);
            Pubsub.publish(PubSubEnum.HIDE_LOADING);
          })
          .finally(() => {
            Pubsub.publish(PubSubEnum.HIDE_LOADING);
          });
        return fileUrl;
      } else {
        const errorText = await uploadResponse.text(); // 获取错误详情
        alert(`File upload failed: ${errorText}`);
      }
    } else {
      alert("Failed to get presigned URL!");
    }
  } catch (error) {
    console.error("文件上传失败", error);
    Pubsub.publish(PubSubEnum.HIDE_LOADING);
  }
};

// 暴露方法给父组件
defineExpose({ chooseFile, uploadFile, handleFileChange });
// 调用父组件方法
const emit = defineEmits(["file-chosen"]);
</script>
<style lang="less" scoped>
.input-frame {
  width: 100%;
  height: 100%;
}
</style>
